"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : ustore-Consistency
Case Name   : 事务中delete-rollback与update-commit并发,delete-commit与update
              -commit并发,重启集群
Create At   : 2022/02/11
Owner       : @zou_jialiang050
Description :
    1.创建表1,为表1创建索引
    2.向表1中插入数据
    3.创建表2并插入数据
    4.线程1开启事务,设置事务隔离级别并删除表1数据后回滚事务
    5.线程2开启事务,设置事务隔离级别,在线程1删除表1数据的同时修改表1数据后
      提交事务
    6.查询表1数据
    7.线程1开启事务,设置事务隔离级别并删除表1数据后提交事务
    8.线程2开启事务,在线程1删除表1数据的同时修改表1数据后提交事务
    9.查询表1数据
    10.重启数据库
    11.联合查询表1,表2数据
    12.向表1中插入数据
    13.修改表1数据
    14.删除表1数据后查询表1数据
    15.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.开启事务成功,设置事务隔离级别成功,删除表1数据成功,回滚事务成功
    5.开启事务成功,设置事务隔离级别成功,修改表1数据成功,提交事务成功
    6.返回查询到的数据
    7.开启事务成功,设置事务隔离级别成功,删除表1数据成功,提交事务成功
    8.开启事务成功,修改表1数据成功,提交事务成功
    9.返回空
    10.成功
    11.返回查询到的数据
    12.插入数据成功
    13.修改表1数据成功
    14.删除表1数据成功,返回查询到的数据
    15.成功
History     :
"""

import os
import time
import unittest
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread


class CONSISTENCY(unittest.TestCase):
    def setUp(self):
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.table1 = 's_ustore_consistency_02.t_ustore_consistency_0014_01'
        self.index = 's_ustore_consistency_02.i_ustore_consistency_0014'
        self.table2 = 's_ustore_consistency_02.t_ustore_consistency_0014_02'
        self.table3 = 's_ustore_consistency_02.t_ustore_consistency_0001_03'
        self.table4 = 's_ustore_consistency_02.t_ustore_consistency_0001_04'

    def test_ustore_consistency(self):
        text1 = 'step1:创建表1,为表1创建索引 expect:成功'
        self.log.info(text1)
        create_table = self.pri_sh.execut_db_sql(
            f'''drop table if exists {self.table1};
            create table {self.table1}(c_id int,
            c_d_id int not null,c_w_id int not null,c_first varchar(16) not 
            null,c_middle char(2),c_last varchar(16) not null,
            c_street_1 varchar(20) not null,c_street_2 varchar(20),
            c_city varchar(20) not null,c_state char(2) not null,
            c_zip char(9) not null,c_phone char(16) not null,
            c_since timestamp,c_credit char(2) not null,c_credit_lim number,
            c_discount number,c_balance number,c_ytd_payment number not null,
            c_payment_cnt int not null,c_delivery_cnt int not null,
            c_data clob not null) with (storage_type=ustore);
            create unique index {self.index} on {self.table1}(c_id,c_d_id,
            c_w_id);''')
        self.log.info(create_table)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, create_table,
                      '执行失败' + text1)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, create_table,
                      '执行失败' + text1)
        self.assertIn(self.constant.CREATE_INDEX_SUCCESS_MSG,
                      create_table, '执行失败' + text1)

        text2 = 'step2:向表1中插入数据 expect:成功'
        self.log.info(text2)
        insert_data = self.pri_sh.execut_db_sql(
            f'''insert into {self.table1} select c_int,c_int,c_int,
            'aaaaa','ab','dafkldafkadbfeod','dafkldafkadbfeodefgh',
            'dafkldafkadbfeodefgh','dafkldafkadbfeodefgh','xy','acgfdagfs',
            'dafkldafkadbfeod',null,'ad',50000.0,0.4491328,-10.0,10.0,1,0,
            lpad('qraogfdamjkfdlhgmdjf',4000,'qraogfdamjkfdlhgmdjf') 
            from {self.table3};''')
        self.log.info(insert_data)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, insert_data,
                      '执行失败' + text2)

        text3 = 'step3:创建表2并插入数据 expect:成功'
        self.log.info(text3)
        create_table = self.pri_sh.execut_db_sql(
            f'''drop table if exists {self.table2};
            create table {self.table2}(
            c_id int,c_d_id int,c_w_id int,c_first varchar(16),
            c_middle char(2),
            c_last varchar(16),c_street_1 varchar(20),c_street_2 varchar(20),
            c_city varchar(20),c_state char(2),c_zip char(9),c_phone char(16),
            c_since timestamp,c_credit char(2),c_credit_lim number,c_discount 
            number,c_balance number,c_ytd_payment number,c_payment_cnt int,
            c_delivery_cnt int,c_data clob);
            insert into {self.table2} select * from {self.table1};''')
        self.log.info(create_table)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, create_table,
                      '执行失败' + text3)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, create_table,
                      '执行失败' + text3)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, create_table,
                      '执行失败' + text3)

        text4 = 'step4:线程1开启事务,设置事务隔离级别并删除表1数据后回滚事务' \
                'expect:开启事务成功,设置事务隔离级别成功,删除表1数据成功' \
                ',回滚事务成功'
        self.log.info(text4)
        start_trans = f'''start transaction;
            set transaction isolation level read committed;
            delete from {self.table1} where c_first='aaaaa';
            select pg_sleep(10);
            rollback;'''
        session1 = ComThread(self.pri_sh.execut_db_sql, args=(start_trans,))
        session1.setDaemon(True)

        text5 = 'step5:线程2开启事务,设置事务隔离级别,在线程1删除表1数' \
                '据的同时修改表1数据,提交事务' \
                'expect:开启事务成功,设置事务隔离级别成功,修改表1数据成功' \
                ',提交事务成功'
        self.log.info(text5)
        start_trans = f'''start transaction;
            set transaction isolation level read committed;
            update {self.table1} set c_id=c_id+10000,
            c_d_id=c_d_id+10000,c_w_id=c_w_id+10000,c_first=c_first||'bb',
            c_data='qraogfdamjkfdlhgmdjf';
            commit;'''
        session2 = ComThread(self.pri_sh.execut_db_sql, args=(start_trans,))
        session2.setDaemon(True)
        session1.start()
        time.sleep(2)
        session2.start()
        session1.join(18)
        session2.join(5)
        result1 = session1.get_result()
        self.log.info(result1)
        result2 = session2.get_result()
        self.log.info(result2)
        self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG,
                      result1, '开启事务失败' + text4)
        self.assertIn(self.constant.SET_SUCCESS_MSG, result1, '执行失败' +
                      text4)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, result1,
                      '执行失败' + text4)
        self.assertIn(self.constant.ROLLBACK_MSG, result1, '执行失败' + text4)
        self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG,
                      result2, '开启事务失败' + text5)
        self.assertIn(self.constant.SET_SUCCESS_MSG, result2, '执行失败' +
                      text5)
        self.assertIn(self.constant.UPDATE_SUCCESS_MSG, result2,
                      '执行失败' + text5)
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, result2, '执行失败' +
                      text5)

        text6 = 'step6:查询表1数据 expect:返回查询到的数据'
        self.log.info(text6)
        select_data = self.pri_sh.execut_db_sql(
            f'''select distinct(c_first),count(c_id) from {self.table1} 
            where c_first='aaaaa' or c_first='aaaaabb' group by c_first 
            order by c_first;''')
        self.log.info(select_data)
        self.assertIn('aaaaabb |  1000', select_data, '执行失败' + text6)

        text7 = 'step7:线程1开启事务,设置事务隔离级别并删除表1数据后提交事务' \
                'expect:开启事务成功,设置事务隔离级别成功,删除表1数据成功' \
                ',提交事务成功'
        self.log.info(text7)
        start_trans = f'''start transaction;
            set transaction isolation level read committed;
            delete from {self.table1} where mod(c_id,2)=0;
            select pg_sleep(10);
            commit;'''
        session1 = ComThread(self.pri_sh.execut_db_sql, args=(start_trans,))
        session1.setDaemon(True)

        text8 = 'step8:线程2开启事务,在线程1删除表1数据的同时修改表1数据,' \
                '提交事务' \
                'expect:开启事务成功,设置事务隔离级别成功,修改表1数据成功' \
                ',提交事务成功'
        self.log.info(text8)
        start_trans = f'''start transaction;
            update {self.table1} set c_id=c_id+10000,
            c_d_id=c_d_id+10000,c_w_id=c_w_id+10000,c_first=c_first||'bb',
            c_data='qraogfdamjkfdlhgmdjf';
            commit;'''
        session2 = ComThread(self.pri_sh.execut_db_sql, args=(start_trans,))
        session2.setDaemon(True)
        session1.start()
        time.sleep(2)
        session2.start()
        session1.join(18)
        session2.join(5)
        result1 = session1.get_result()
        self.log.info(result1)
        result2 = session2.get_result()
        self.log.info(result2)
        self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG,
                      result1, '开启事务失败' + text7)
        self.assertIn(self.constant.SET_SUCCESS_MSG, result1, '执行失败' +
                      text7)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, result1,
                      '执行失败' + text7)
        self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG,
                      result2, '开启事务失败' + text8)
        self.assertIn(self.constant.UPDATE_SUCCESS_MSG, result2,
                      '执行失败' + text8)
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, result2, '执行失败' +
                      text8)

        text9 = 'step9:查询表1数据 expect:返回空'
        self.log.info(text9)
        select_data = self.pri_sh.execut_db_sql(
            f'''select distinct(c_first),count(c_id) from {self.table1} 
            where c_first='aaaaa' group by c_first order by c_first;''')
        self.log.info(select_data)
        self.assertIn('(0 rows)', select_data, '执行失败' + text9)

        text10 = 'step10:重启数据库 expect:成功'
        self.log.info(text10)
        msg = self.pri_sh.restart_db_cluster()
        self.log.info(msg)
        self.assertTrue(msg, '执行失败' + text10)

        text11 = 'step11:联合查询表1,表2数据 expect:返回查询到的数据'
        self.log.info(text11)
        select_data = self.pri_sh.execut_db_sql(f'''
            select distinct(c_first),count(c_id) from {self.table1} where 
            c_first='aaaaa' group by c_first order by c_first;
            select c_id,c_d_id,c_w_id,c_first,c_middle,c_last,c_street_1,
            c_street_2,c_city,c_state,c_zip,c_phone,c_since,c_credit,
            c_credit_lim,c_discount,c_balance,c_ytd_payment,c_payment_cnt,
            c_delivery_cnt from {self.table1} minus select c_id,c_d_id,
            c_w_id,c_first,c_middle,c_last,c_street_1,c_street_2,c_city,
            c_state,c_zip,c_phone,c_since,c_credit,c_credit_lim,c_discount,
            c_balance,c_ytd_payment,c_payment_cnt,c_delivery_cnt from 
            {self.table2};
            select c_id,c_d_id,c_w_id,c_first,c_middle,c_last,c_street_1,
            c_street_2,c_city,c_state,c_zip,c_phone,c_since,c_credit,
            c_credit_lim,c_discount,c_balance,c_ytd_payment,c_payment_cnt,
            c_delivery_cnt from {self.table2} minus select c_id,c_d_id,c_w_id,
            c_first,c_middle,c_last,c_street_1,c_street_2,c_city,c_state,
            c_zip,c_phone,c_since,c_credit,c_credit_lim,c_discount,
            c_balance,c_ytd_payment,c_payment_cnt,c_delivery_cnt from
            {self.table1};''')
        self.log.info(select_data)
        self.assertIn('(0 rows)', select_data, '执行失败' + text8)
        self.assertIn('(500 rows)', select_data, '执行失败' + text8)
        self.assertIn('(1000 rows)', select_data, '执行失败' + text8)

        text12 = 'step12:向表1插入数据 expect:成功'
        self.log.info(text12)
        insert_data = self.pri_sh.execut_db_sql(
            f'''insert into {self.table1} select * from {self.table4};''')
        self.log.info(insert_data)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, insert_data,
                      '执行失败' + text12)

        text13 = 'step13:修改表1数据 expect:修改表1数据成功'
        self.log.info(text13)
        update_data = self.pri_sh.execut_db_sql(
            f'''update {self.table1} set c_id=c_id+10000,
            c_d_id=c_d_id+10000,c_w_id=c_w_id+10000,c_first=c_first||'bb',
            c_data='qraogfdamjkfdlhgmdjf';''')
        self.log.info(update_data)
        self.assertIn(self.constant.UPDATE_SUCCESS_MSG, update_data,
                      '执行失败' + text13)

        text14 = 'step14:删除表1数据后查询表1数据 expect:删除表1数据成功,' \
                 '返回查询到的数据'
        self.log.info(text14)
        select_data = self.pri_sh.execut_db_sql(
            f'''delete from {self.table1} where mod(c_id,2)=0;
            select distinct c_first,count(c_id),sum(c_id) from {self.table1}
            where c_first='aaaaa' or c_first='aaaaabb' or c_first='aaaaabbbb' 
            or c_first='aaaaabbbbbb' group by c_first order by c_first;''')
        self.log.info(select_data)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, select_data, '执行失败'
                      + text10)
        self.assertIn('aaaaabb     |   500 |  5250000', select_data,
                      '执行失败' + text14)
        self.assertIn('aaaaabbbbbb |   500 | 15250000', select_data,
                      '执行失败' + text14)

    def tearDown(self):
        text15 = 'step15:清理环境 expect:成功'
        self.log.info(text15)
        clean_environment = self.pri_sh.execut_db_sql(
            f'''drop table {self.table1} cascade;
            drop table {self.table2} cascade;''')
        self.log.info(clean_environment)
        self.assertEqual(clean_environment.count
                         (self.constant.TABLE_DROP_SUCCESS), 2,
                         '执行失败' + text15)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
